package com.findsing.jetty.websocket.client.endpoints;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.HandshakeResponse;
import javax.ws.rs.core.NewCookie;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import com.findsing.jetty.websocket.server.config.WebSocketConfig;

public class ClientEndpointConfigurator extends ClientEndpointConfig.Configurator {
	private static final Logger logger = Logger.getLogger(WebSocketConfig.class.getName());
	private static List<NewCookie> cookies = null;
	public static void setCookies(List<NewCookie> cookies) {
		ClientEndpointConfigurator.cookies = cookies;
	}
	public static List<NewCookie> getCookies() {
		return cookies;
	}

	@Override
	public void beforeRequest(Map<String, List<String>> headers) {
		headers.put("user-agent", Collections.singletonList("WebSocket Client"));
		headers.put("Authorization", Collections.singletonList("Basic " + getAuthenticationToken()));
		if(null != cookies)
		{
			List<String> cookieList = new ArrayList<String>();
			for(NewCookie cookie: cookies)
			{
				cookieList.add(cookie.toString());
			}
			headers.put("Cookie", cookieList);
		}
	}
	
	@Override
	public void afterResponse(HandshakeResponse response) {
        Map<String, List<String>> headers = response.getHeaders();
        Iterator<String> names = headers.keySet().iterator();
        while(names.hasNext())
        {
        	String name = names.next();
        	List<String> values = headers.get(name);
        	for(String value: values)
        	{
        		logger.info(String.format("%s: %s", name, value));
        	}
        }
	}

	protected String getAuthenticationToken()
	{
		try
		{
			return new String(Base64.encodeBase64("jeff:password".getBytes()), "UTF-8");
		}
		catch(UnsupportedEncodingException e)
		{
			logger.error(e.getMessage(), e);
		}
		
		return null;
	}
}
